package logic

import (
	"context"
	"fmt"
	"math/rand"
	"novel/model/cache"
	"novel/model/mysql"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("您的验证码错误,请重新发送后继续登录")
	}

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		user = mysql.User{
			Account:  in.Account,
			Password: in.Password,
			Image:    "https://cn.bing.com/images/search?q=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&FORM=IQFRBA&id=98A7E8CAD656E25BA5D30AAD09F55A0FC89E9072",
			Name:     fmt.Sprintf("%s_%d", "游客", rand.Intn(100000)),
		}
		mysql.DB.Debug().Create(&user)
	} else {
		if user.Password != in.Password {
			return nil, fmt.Errorf("您输入的密码不正确")
		}
	}

	return &novelrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
